package com.xqyq.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xqyq.model.User;


@WebFilter(
		urlPatterns = {"/user/*",},   //禁止未登录用户访问
		initParams = { @WebInitParam(name = "LOGIN_VIEW", value = "/xqyq/login.html" )}
		)
public class UserFilter implements Filter {
	private String LOGIN_VIEW;
	public void init(FilterConfig config) throws ServletException {
		this.LOGIN_VIEW = config.getInitParameter("LOGIN_VIEW");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		String referer = req.getHeader("referer");
		User user = (User) req.getSession().getAttribute("user");
		if(referer==null||!referer.contains(req.getServerName())||user==null){
			resp.sendRedirect(LOGIN_VIEW);
		}
		else {
			chain.doFilter(request, response);
		}
	}
	public void destroy(){	
	}
}
